package org.kabanyo.components {
	import flash.events.MouseEvent;

	import mx.core.IFactory;

	import spark.components.Button;
	import spark.components.Group;
	import spark.components.SkinnableContainer;

	//SkinState
	[SkinState("expanded")]

	/**
	 * Container with collapsed and expanded states.
	 * @author Desky Natalio
	 *
	 */

	public class ExpandableContainer extends SkinnableContainer {

		//SkinPart
		[SkinPart(required = "false")]
		public var expandGroup:Group;
		[SkinPart(required = "false")]
		public var expandButton:Button;

		//New Property
		private var _collapsed:Boolean = true;

		[Bindable]
		public function get collapsed():Boolean {
			return _collapsed;
		}

		public function set collapsed(value:Boolean):void {
			_collapsed = value;
			invalidateSkinState();

		}

		private var _collapsedWidth:Number;

		public function get collapsedWidth():Number {
			return _collapsedWidth;
		}

		private var _collapsedHeight:Number;

		public function get collapsedHeight():Number {
			return _collapsedHeight;
		}

		private var _expandRenderer:IFactory;

		public function get expandRenderer():IFactory {
			return _expandRenderer;
		}

		public function set expandRenderer(value:IFactory):void {
			_expandRenderer = value;
		}

		//Constructor
		public function ExpandableContainer() {
			super();
		}

		//Override Method
		override protected function getCurrentSkinState():String {
			if (!enabled) {
				return "disabled";
			} else if (!collapsed) {
				return "expanded";
			} else {
				return "normal";
			}
		}

		override protected function partAdded(partName:String, instance:Object):void {
			super.partAdded(partName, instance);
			if (instance == expandButton) {
				expandButton.addEventListener(MouseEvent.CLICK, expandButton_clickHandler);
			}
			if (instance == expandGroup) {
				expandGroup.addElement(expandRenderer.newInstance());
			}
		}

		override protected function partRemoved(partName:String, instance:Object):void {
			super.partRemoved(partName, instance);
			if (instance == expandButton) {
				expandButton.removeEventListener(MouseEvent.CLICK, expandButton_clickHandler);
			}
		}

		//New Method
		public function toggle():void {
			if (collapsed) {
				collapsed = false;
			} else {
				collapsed = true;
			}

			invalidateSkinState();
		}

		//Event Handler
		private function expandButton_clickHandler(event:MouseEvent):void {
			toggle();
		}
	}
}
